package com.nfu.zlsp.dev.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nfu.zlsp.dev.common.utils.OrderIdUtil;
import com.nfu.zlsp.dev.common.utils.PageUtils;
import com.nfu.zlsp.dev.common.utils.Query;
import com.nfu.zlsp.dev.common.utils.R;
import com.nfu.zlsp.dev.dao.AddressDao;
import com.nfu.zlsp.dev.dao.TOrderDao;
import com.nfu.zlsp.dev.dao.TransportDao;
import com.nfu.zlsp.dev.dao.UserDao;
import com.nfu.zlsp.dev.entity.AddressEntity;
import com.nfu.zlsp.dev.entity.TOrderEntity;
import com.nfu.zlsp.dev.entity.TransportEntity;
import com.nfu.zlsp.dev.entity.UserEntity;
import com.nfu.zlsp.dev.entity.vo.OrderManagementConsignVo;
import com.nfu.zlsp.dev.entity.vo.OrderManagementTransportVo;
import com.nfu.zlsp.dev.service.AddressService;
import com.nfu.zlsp.dev.service.TOrderService;
import com.nfu.zlsp.dev.service.TransportService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("tOrderService")
public class TOrderServiceImpl extends ServiceImpl<TOrderDao, TOrderEntity> implements TOrderService {

    @Autowired
    private TransportDao transportDao;


    @Autowired
    private UserDao userDao;

    @Autowired
    private AddressService addressService;

    @Autowired
    private AddressDao addressDao;

    @Autowired
    private TOrderDao tOrderDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TOrderEntity> page = this.page(
                new Query<TOrderEntity>().getPage(params),
                new QueryWrapper<TOrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryOrderManagementConsignPage(Map<String, Object> params) {

        String creationTime = (String) params.get("creationTime");
        String unloadCity = (String) params.get("unloadCity");
        String logisticsType = (String) params.get("logisticsType");

        QueryWrapper<TransportEntity> queryWrapper = new QueryWrapper<TransportEntity>();
        queryWrapper.orderByDesc("creation_time");
        if (unloadCity == null){
            queryWrapper.eq("t_user", params.get("t_user")).eq("state", "1");
        }else {
            queryWrapper.eq("t_user", params.get("t_user")).eq("state", "1")
                    .eq("logistics_type",logisticsType);
        }
        List<TransportEntity> transportEntityList = transportDao.selectList(queryWrapper);

        List<OrderManagementTransportVo> orderManagementTransportVoList = transportEntityList.stream().map(transportEntity -> {
            QueryWrapper<TOrderEntity> q = new QueryWrapper<TOrderEntity>();

            if (unloadCity == null) {
                q.eq("t_id", transportEntity.getId());
            }else{
                q.eq("t_id", transportEntity.getId()).gt("creation_time",creationTime);
            }

            TOrderEntity tOrderEntity = this.baseMapper.selectOne(q);
            OrderManagementTransportVo orderManagementTransportVo = new OrderManagementTransportVo();
            if (tOrderEntity != null) {
                BeanUtils.copyProperties(transportEntity, orderManagementTransportVo);
                //拷贝 tOrderEntity到vo
                orderManagementTransportVo.setCCargoInfo(tOrderEntity.getCCargoInfo());
                orderManagementTransportVo.setTId(tOrderEntity.getTId());
                orderManagementTransportVo.setCreationTime(tOrderEntity.getCreationTime());
                orderManagementTransportVo.setCUserid(tOrderEntity.getCUserid());
                orderManagementTransportVo.setLogisticsInfo(tOrderEntity.getLogisticsInfo());
                orderManagementTransportVo.setLogisticsState(tOrderEntity.getLogisticsState());
                orderManagementTransportVo.setOrderState(tOrderEntity.getOrderState());
                orderManagementTransportVo.setContractState(tOrderEntity.getContractState());
                //查询承运方公司
                UserEntity userEntity = userDao.selectOne(new QueryWrapper<UserEntity>().eq("id", tOrderEntity.getCUserid()));
                orderManagementTransportVo.setCompany(userEntity.getCompany() + "(" + userEntity.getNumber() + ")");

                //订单编号
                orderManagementTransportVo.setOrderId(tOrderEntity.getId());

                //根据地区编号查赋予细地址
                String pickAddress = addressService.getAddressByRegionId(tOrderEntity.getCPickupAddress());
                String unloadAddress = addressService.getAddressByRegionId(tOrderEntity.getCUnloadAddress());
                pickAddress += tOrderEntity.getCPickupDetailAddress();
                unloadAddress += tOrderEntity.getCUnloadDetailAddress();
                orderManagementTransportVo.setPickupDetailAddress(pickAddress);
                orderManagementTransportVo.setUnloadDetailAddress(unloadAddress);


                if (unloadCity != null) {
                    /**
                     * 删选出地址不符合查询条件的
                     *  返回空的QueryTransportVo
                     */
                    AddressEntity endCity = addressDao.selectOne(new QueryWrapper<AddressEntity>().eq("address_areaId", tOrderEntity.getCUnloadAddress()));
                    if(!endCity.getAddressRegionid().equals(unloadCity)){
                        //地址条件不符
                        return new OrderManagementTransportVo();
                    }
                }
                return orderManagementTransportVo;

            }else {
                return new OrderManagementTransportVo();
            }

        }).collect(Collectors.toList());


        //用迭代器删除值为空的元素（迭代器遍历不会报错 foreach会）
        Iterator iterator = orderManagementTransportVoList.iterator();
        while (iterator.hasNext()){
            OrderManagementTransportVo vo = (OrderManagementTransportVo) iterator.next();
            if(vo.getId() == null){
                iterator.remove();
            }

        }

        IPage<TOrderEntity> page = this.page(
                new Query<TOrderEntity>().getPage(params),
                new QueryWrapper<TOrderEntity>()
        );


        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(orderManagementTransportVoList);

        System.out.println("hhhhhhhhhhhhhhhhhhhhh:" + pageUtils.getList());
        return pageUtils;

    }

    @Override
    public R savePayList(Map<String, Object> params) {
        TOrderEntity tOrderEntity = new TOrderEntity();
        tOrderEntity.setId(OrderIdUtil.getOrderId());
        tOrderEntity.setTId((String) params.get("tId"));
        tOrderEntity.setCreationTime(new Date());
        tOrderEntity.setCUserid((String) params.get("c_userid"));
        tOrderEntity.setCCargoInfo((String) params.get("cargoInfo"));
        tOrderEntity.setCPickupAddress((String) params.get("pickupAddress"));
        tOrderEntity.setCUnloadAddress((String) params.get("unloadAddress"));
        tOrderEntity.setCPickupDetailAddress((String) params.get("pickupDetailAddress"));
        tOrderEntity.setCUnloadDetailAddress((String) params.get("unloadDetailAddress"));
        tOrderEntity.setLogisticsState(1);
        tOrderEntity.setOrderState(0);
        tOrderEntity.setContractState(1);
        int insert = this.baseMapper.insert(tOrderEntity);
        if(insert >= 1){
            int result = transportDao.updateStateById(tOrderEntity.getTId());
            if (result >= 1){
                return R.ok();
            }
        }
        return R.ok().put("data","更新数据失败");
    }

    @Override
    public PageUtils queryMyOrderConsignPage(Map<String, Object> params) {

        String creationTime = (String) params.get("creationTime");
        String unloadCity = (String) params.get("unloadCity");
        String logisticsType = (String) params.get("logisticsType");
        QueryWrapper<TOrderEntity> queryWrapper = new QueryWrapper<TOrderEntity>();

        queryWrapper.orderByDesc("creation_time");

        if (unloadCity == null) {
            queryWrapper.eq("c_userid", params.get("c_userid"));
        }else{
            queryWrapper.eq("c_userid", params.get("c_userid")).gt("creation_time",creationTime);
        }
        List<TOrderEntity> tOrderEntityList = tOrderDao.selectList(queryWrapper);

        List<OrderManagementTransportVo> orderManagementTransportVoList = tOrderEntityList.stream().map(tOrderEntity -> {
            OrderManagementTransportVo orderManagementTransportVo = new OrderManagementTransportVo();

            //查询承运方公司和联系方式并写入
            QueryWrapper<TransportEntity> q = new QueryWrapper<TransportEntity>();

            if (unloadCity == null) {
                q.eq("id", tOrderEntity.getTId());
            }else{
                q.eq("id", tOrderEntity.getTId()).eq("logistics_type",logisticsType);
            }

            TransportEntity transportEntity = transportDao.selectOne(q);
            if (transportEntity != null) {
                UserEntity userEntity = userDao.selectOne(new QueryWrapper<UserEntity>().eq("id", transportEntity.getTUser()));

                orderManagementTransportVo.setCompany(userEntity.getCompany() + "("+userEntity.getNumber()+")");

                //拷贝transport
                BeanUtils.copyProperties(transportEntity, orderManagementTransportVo);
                orderManagementTransportVo.setOrderId(transportEntity.getId());
                orderManagementTransportVo.setCreationTime(tOrderEntity.getCreationTime());
                orderManagementTransportVo.setOrderId(tOrderEntity.getId());
                orderManagementTransportVo.setLogisticsInfo(tOrderEntity.getLogisticsInfo());
                orderManagementTransportVo.setLogisticsState(tOrderEntity.getLogisticsState());
                orderManagementTransportVo.setOrderState(tOrderEntity.getOrderState());
                orderManagementTransportVo.setContractState(tOrderEntity.getContractState());

                orderManagementTransportVo.setCCargoInfo(tOrderEntity.getCCargoInfo());
                orderManagementTransportVo.setUnloadDetailAddress(tOrderEntity.getCUnloadDetailAddress());
                orderManagementTransportVo.setPickupDetailAddress(tOrderEntity.getCPickupDetailAddress());

                //根据地区编号查赋予细地址
                String pickAddress = addressService.getAddressByRegionId(tOrderEntity.getCPickupAddress());
                String unloadAddress = addressService.getAddressByRegionId(tOrderEntity.getCUnloadAddress());
                pickAddress += tOrderEntity.getCPickupDetailAddress();
                unloadAddress += tOrderEntity.getCUnloadDetailAddress();
                orderManagementTransportVo.setPickupDetailAddress(pickAddress);
                orderManagementTransportVo.setUnloadDetailAddress(unloadAddress);


                if (unloadCity != null) {
                    /**
                     * 删选出地址不符合查询条件的
                     *  返回空的QueryTransportVo
                     */
                    AddressEntity endCity = addressDao.selectOne(new QueryWrapper<AddressEntity>().eq("address_areaId", tOrderEntity.getCUnloadAddress()));
                    if(!endCity.getAddressRegionid().equals(unloadCity)){
                        //地址条件不符
                        return new OrderManagementTransportVo();
                    }
                }
                return orderManagementTransportVo;
            }else{
                return new OrderManagementTransportVo();
            }

        }).collect(Collectors.toList());

        //用迭代器删除值为空的元素（迭代器遍历不会报错 foreach会）
        Iterator iterator = orderManagementTransportVoList.iterator();
        while (iterator.hasNext()){
            OrderManagementTransportVo vo = (OrderManagementTransportVo) iterator.next();
            if(vo.getId() == null){
                iterator.remove();
            }

        }

        IPage<TOrderEntity> page = this.page(
                new Query<TOrderEntity>().getPage(params),
                new QueryWrapper<TOrderEntity>()
        );

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(orderManagementTransportVoList);
        System.out.println("ooooooooooooooooooooooooo:" + orderManagementTransportVoList);
        return pageUtils;
    }

    @Override
    public R updateOrderStateById(String id) {

        TOrderEntity tOrderEntity = this.baseMapper.selectById(id);
        if (tOrderEntity != null) {
            if (tOrderEntity.getOrderState() == 1){
                return R.ok().put("data","已确定收货,无需重复收获");
            }else {
                int result = tOrderDao.updateOrderStateById(id);
                if (result >= 1){
                    return R.ok().put("data","确定收货成功");
                }else {
                    return R.ok().put("data","系统繁忙,收货失败,请稍后重试");
                }
            }


        }else {
            return R.ok().put("data","系统繁忙,稍后重试");
        }




    }

}























